<?php

/**
 * question actions.
 *
 * @subpackage question
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class questionActions extends sfActions
{
	// TODO: change all hint to constant!

	public function executeAnswer(sfWebRequest $request) {
	}

	public function executeGetQuestions(sfWebRequest $request) {
		//$data0 = '{"questions": []}';
		//$data1 = '{"questions": [{"id":9, "question":"What the hell?!"}]}';
		//$data2 = '{"questions": [{"id":12, "question":"what"}, {"id":23, "question":"who"}]}';
		if (!$this->getUser()->isAuthenticated()) {
			$data = '{"redirect":"../user/login"}';
			return $this->renderPartial('new_response', array('json_data' => $data));
		}
		
		$temp = new SeecUnansweredQuestion();
		$userID = $this->getUser()->getAttribute('user_id');
		$questions = $temp->unansweredQuestion($userID);

		$data = array();

		$num = count($questions);
		if ($num > 10)
			$num = 10;
		for ($i=0; $i<$num; $i++) {
			$questionID = $questions[$i]["question_id"];

			$query = Doctrine_Query::create()
			->select('*')
			->from ('SeecQuestion SQ')
			->where('SQ.id = ?', $questionID)->execute();

			$question = $query->toArray();
			$questionContent = $question[0]["content"];
			$questionContent = $this->checkString($questionContent);
			$data[$questionID] = $questionContent;
		}

		$formatData = "{\"questions\": [";
		foreach ($data as $key => $value) {
			$formatData .= "{\"id\":";
			$formatData .= $key;
			$formatData .= ", \"question\":\"";
			$formatData .= $value;
			$formatData .= "\"},";
		}
		if ($num!==0) {
			$formatData = substr($formatData, 0, -1);
		}
		$formatData .= "]}";

			
		return $this->renderPartial('new_response', array('json_data' => $formatData));
	}

	public function executeAnswerQuestion(sfWebRequest $request) {
		$questionID = $request->getParameter('q');
		$answer = $request->getParameter('a');
		
		$userID = $this->getUser()->getAttribute('user_id');

		$answerEntity = new SeecAnswer();
		$answerEntity->content=$answer;
		$answerEntity->user_id=$userID;
		$answerEntity->question_id=$questionID;
		$answerEntity->save();
		
		$query = Doctrine_Query::create()
		->select ('*')
		->from ('SeecUnansweredQuestion SUQ')
		->where ('SUQ.question_id = ?', $questionID)->execute();
		
		$ifExist = $query->count();
		
		if ($ifExist !==0) {
			$query2 = Doctrine_Query::create()
			->delete ('SeecUnansweredQuestion SUQ')
			->where ('SUQ.question_id = ? AND SUQ.user_id = ?', array($questionID, $userID))->execute();
		}
	}

	public function executeHelpAnswering(sfWebRequest $request) {
		$questionID = $request->getParameter('q');

		$query = Doctrine_Query::create()
		->select('*')
		->from ('SeecQuestion SQ')
		->where('SQ.id = ?', $questionID)->execute();

		$question = $query->toArray();
		$questionContent = $question[0]["content"];

		$temp = new SeecQuestion();
		$yahooResults = $temp->getResultsBySearchEngine($questionContent);
		$yahooResultNum = count($yahooResults["title"]);
		
		$formatData = "{\"retrievals\": [";
		for ($i=0; $i<$yahooResultNum; $i++) {
			$title = $yahooResults["title"][$i];
			$url = $yahooResults["url"][$i];
			$summary = $yahooResults["abstract"][$i];
			
			$title = $this->checkString($title);
			$url = $this->checkString($url);
			$summary = $this->checkString($summary);

			
			$formatData .= "{\"title\":\"";
			$formatData .= $title;
			$formatData .= "\", \"url\":\"";
			$formatData .= $url;
			$formatData .= "\", \"summary\":\"";
			$formatData .= $summary;
			$formatData .= "\"},";
		}
		if ($yahooResultNum !==0) {
			$formatData = substr($formatData, 0, -1);
		}
		$formatData .= "]}";
		
		$data0 = '{"retrievals": []}';
		$data1 = '{"retrievals": [{"title":"Java island", "url":"http.en.wikipedia.org", "summary":"Java island, a good place to visit"}]}';
		

		return $this->renderPartial('new_response', array('json_data' => $formatData));
	}

	/**
	 * do nothing, display the page for "ask" action
	 *
	 * @param sfWebRequest $request
	 */
	public function executeAsk(sfWebRequest $request) {
		if (!$this->getUser()->isAuthenticated()) {
		    $this->redirect('user/login');
		}
	}

	/**
	 * 	if isXmlHttpRequest then
	 * 		q <- question from request
	 * 		if q isNotValid then
	 * 			return and give "invalid question"
	 * 		else
	 * 			cset <- model.getCategory(question)
	 * 			lset <- model.getLabel(question)
	 * 			let template handler process
	 * 	else
	 * 		return and give "bad request"
	 *
	 * @param sfWebRequest $request
	 */
	public function executeSubmit(sfWebRequest $request) {
		if($request->isXmlHttpRequest()) {
			$question = $request->getParameter('q');
			if(!$this->isValidQuestion($question)) {
				echo 'TO REDIRECT!';
			} else {
				$getCategory = new SeecQuestion();
				$category = $getCategory->saveQuestion($question);
				return $this->renderPartial('response', array(
					'id' => 'category',
					'value' => $category));
			}
		} else {
			echo 'TO REDIRECT!';
		}
	}

	/**
	 * 	if isXmlHttpRequest then
	 * 		cset <- categories from request
	 * 		lset <- labels from request
	 * 		if cset isValid and lset isValid then
	 * 			a <- get answer from model
	 * 			if a == null then
	 * 				return and give "seec sent the question to # people"
	 * 			else
	 * 				render answer with "helpful or not"
	 * 		else
	 * 			return and give "bad category or label"
	 * 	else
	 * 		return and give "bad request"
	 *
	 * @param sfWebRequest $request
	 */
	public function executeConfirm(sfWebRequest $request) {
		if ($request->isXmlHttpRequest()) {
			$question = $request->getParameter('q');
			$category = $request->getParameter('c');
			if ($this->isValidFeedback($category)) {

				$temp1 = new SeecQuestion();
				$simQ = $temp1->calculateSimilarity($question);

				$query = Doctrine_Query::create()
				->select('*')
				->from ('SeecAnswer SA, SeecQuestion SQ')
				->where('SQ.content = ? AND SA.question_id = SQ.id', $simQ);

				$answerArray = $query->execute()->toArray();
				$answer = $answerArray[0];

				$questionEntity = new SeecQuestion();
				$questionEntity->content=$question;
				$userID = $this->getUser()->getAttribute('user_id');
				$questionEntity->user_id=$userID;
				$questionEntity->category_name=$category;
				$questionEntity->save();

				if($answer == null) {
					$number = $this->sendToUser($request);
					//$temp2 = new SeecUserCategory();
					//$number = $temp2->getNumberOfPotentialUser($category);
					return $this->renderPartial('response', array(
						'id' => 'number',
						'value' => $number));
				} else {
					return $this->renderPartial('response', array(
						'id' => 'answer',
						'value' => $answer["content"]));
				}
			} else {
				echo 'TO REDIRECT!';
			}
		} else {
			echo 'TO REDIRECT!';
		}
	}

	/**
	 * TODO: logic is not complete
	 *
	 * 	if isXmlHttpRequest then
	 * 		notice database!
	 * 		return success hint?
	 *  else
	 *  	return bad request hint
	 *
	 * @param sfWebRequest $request
	 */
	public function executeHelpful(sfWebRequest $request) {
		if($request->isXmlHttpRequest()) {
			$question = $request->getParameter('q');
			$answer = $request->getParameter('a');

			$query = Doctrine_Query::create()
			->select('*')
			->from ('SeecQuestion SQ')
			->where('SQ.content = ?', $question)->execute();

			$questionArrayNum = $query->count();
			$questionArray = $query->toArray();
			$questionID = $questionArray[$questionArrayNum-1]["id"];

			$answerEntity = new SeecAnswer();
			$answerEntity->content=$answer;
			$userID = $this->getUser()->getAttribute('user_id');
			$answerEntity->user_id=$userID;
			$answerEntity->question_id=$questionID;
			$answerEntity->save();

			return $this->renderPartial('response', array(
				'id' => 'null', 
				'value' => 'null'));;
		} else {
			echo 'TO REDIRECT!';
		}
	}

	/**
	 * TODO: logic is not complete
	 *
	 * 	if isXmlHttpRequest then
	 * 		send answer to others
	 * 		return send to # of potential respondent
	 *  else
	 *  	return bad request hint
	 *
	 * @param sfWebRequest $request
	 */
	public function executeBadAnswer(sfWebRequest $request) {
		if($request->isXmlHttpRequest()) {
			// where is columbia university? how can i get there by m60?

			$number = $this->sendToUser($request);

			return $this->renderPartial('response', array(
				'id' => 'number',
				'value' => $number));
		} else {
			echo 'TO REDIRECT!';
		}
	}


	/**
	 * STUB!
	 * TODO: server side validator, before pass it to model
	 * 		maybe useless.
	 * @param $question
	 */
	protected function isValidQuestion($question)
	{
		if(strlen($question) < 8) return false;
		return true;
	}

	/**
	 * STUB!
	 * TODO: check is category and labels valid from user
	 * 		feedback
	 * @param $category
	 * @param $labels
	 */
	protected function isValidFeedback($category, $labels)
	{
		return true;
	}

	/**
	 * STUB!
	 * TODO: get answer with feedback category and labels from model
	 *
	 * @param $question
	 * @param $category
	 * @param $labels
	 */
	protected function getAnswer($question, $category)
	{
		if(rand(0, 100) > 50)
		return 'Oh shit!';
		else
		return null;
	}

	/**
	 * STUB!
	 * TODO: get number of potential respondents from model
	 *
	 * @param $question
	 * @param $category
	 * @param $labels
	 */
	protected function getPotentialNumber($question, $category)
	{
		return rand(5, 100);
	}

	/**
	 * STUB!
	 * TODO: send question to model,
	 * 		and get a collection of categories
	 * @param $question
	 */
	protected function getCategory($question)
	{
		$seec_categories = Doctrine::getTable('SeecCategory')
		->createQuery('a')
		->execute();
		if($seec_categories->count() > 0)
		{
			$i = rand(0, $seec_categories->count() - 1);
			return $seec_categories[$i];
		}
		else
		{
			return null;
		}
	}

	/**
	 * STUB!
	 * TODO: send question to model?
	 * 		return a collection of labels
	 * @param $question
	 */
	protected function getLabel($question)
	{
		$arr = preg_split('/ /', $question);
		if(count($arr) > 3)
		{
			for($i = 0; $i < 3; $i++)
			{
				$ret[$i] = $arr[rand(0, count($arr) - 1)];
			}
			return $ret;
		}
		else
		{
			return $arr;
		}
	}

	protected function sendToUser($request)
	{
		$myUserID = $this->getUser()->getAttribute('user_id');
		
		$question = $request->getParameter('q');
			
		$query = Doctrine_Query::create()
		->select('*')
		->from ('SeecQuestion SQ')
		->where('SQ.content = ?', $question)->execute();

		$questionArrayNum = $query->count();
		$questionArray = $query->toArray();
		$questionID = $questionArray[$questionArrayNum-1]["id"];
		$questionCateName = $questionArray[$questionArrayNum-1]["category_name"];

		$temp3 = new SeecUserCategory();
		$number = $temp3->getNumberOfPotentialUser($questionCateName);
		$temp4 = new SeecUser();
		$users = $temp4->getPotentialUser($questionCateName);
		
		$numberFlag = 0;
		
		for($i=0; $i<$number; $i++) {
			$userID = $users[$i]["id"];
			if(strcmp($userID, $myUserID) !== 0) {
				$unansweredEntity = new SeecUnansweredQuestion();
				$unansweredEntity->user_id = $userID;
				$unansweredEntity->question_id = $questionID;
				$unansweredEntity->save();
			} else {
				$numberFlag = 1;
			}
		}
		if ($numberFlag == 1) {
			$number -=1;
		}
		return $number;
	}
	
	protected function checkString($input) {
		$input = str_replace("\\","\\\\",$input);
		$input = str_replace("\"","\\\"",$input);
		$input = str_replace("\'","\\\'",$input);
		$input = str_replace("<","&lt;",$input);
		$input = str_replace(">","&gt;",$input);
		return $input;
	}
}
